package com.siae.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siae.mapper.ItemMapper;
import com.siae.mapper.UserItemMapper;
import com.siae.pojo.Audit;
import com.siae.pojo.Item;
import com.siae.pojo.Message;
import com.siae.pojo.UserItem;
import com.siae.pojo.vo.Result;
import com.siae.service.ItemService;
import com.siae.service.UserItemService;
import com.siae.utils.BizCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserItemServiceImpl extends ServiceImpl<UserItemMapper, UserItem> implements UserItemService {
    private final ItemService itemService;

    @Autowired
    public UserItemServiceImpl(ItemService itemService) {
        this.itemService = itemService;
    }
    @Autowired
    private UserItemMapper userItemMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private UserServiceImpl userService;


    @Override
    public Result<List<Map>> getAllItems(String name,Integer userId,Integer itemId) {
        try {
            // 创建条件对象，设置查询条件参数
            QueryWrapper<UserItem> wrapper = new QueryWrapper<>();
            wrapper.like(StringUtils.isNotBlank(name),"name",name)
                    .eq(userId != null && userId != 0,"user_id",userId)
                    .eq(itemId != null && itemId != 0,"item_id",itemId);
            // 执行查询操作
            List<UserItem> userItems = this.userItemMapper.selectList(wrapper);
            List<Map> userItemList = userItems.stream()
                    .map(userItem -> {
                        Map userItemMap = getUserItemMap(userItem);
                        return userItemMap;
                    }).collect(Collectors.toList());
            return Result.success(BizCode.SUCCESS,userItemList);
        } catch (Exception e){
            e.printStackTrace();
            log.error("查询团队信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
    private Map getUserItemMap(UserItem userItem){
        Map userItemMap = new HashMap<>();
        userItemMap.put("id",userItem.getId());
        userItemMap.put("name",userItem.getName());
        userItemMap.put("userName",getUserName(userItem.getUserId()));
        userItemMap.put("userNameOne",getUserName(userItem.getUserIdOne()));
        userItemMap.put("userNameTwo",getUserName(userItem.getUserIdTwo()));
        userItemMap.put("userNameThree",getUserName(userItem.getUserIdThree()));
        userItemMap.put("itemName",itemService.getItemById(userItem.getItemId()).getData().get("name").toString());
        userItemMap.put("createdAt",userItem.getCreatedAt());
        userItemMap.put("updatedAt",userItem.getUpdatedAt());
        userItemMap.put("isDel",userItem.getIsDel());
        return userItemMap;
    }
    private String getUserName(Integer userId){
        return userService.getUserById(userId).getData().getUserName();
    }

    @Override
    public Result<UserItem> getUserItemByName(String name) {
        try {
            QueryWrapper<UserItem> wrapper = new QueryWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(name),"name",name);
            UserItem userItem = userItemMapper.selectOne(wrapper);
            return Result.success(BizCode.SUCCESS,userItem);
        } catch (Exception e){
            e.printStackTrace();
            log.error("查询团队信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result<UserItem> getItemById(Integer id) {
        try {
            UserItem userItem = this.userItemMapper.selectById(id);
            return Result.success(BizCode.SUCCESS,userItem);
        } catch (Exception e){
            e.printStackTrace();
            log.error("查询团队信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
    public Integer getUserId(String userName){
        Integer id = userService.getUserByName(userName).getData().getId();
        return id;
    }


    @Override
    public Result addItem(Map dateMap) {
        try {
            UserItem userItemName = getUserItemByName(dateMap.get("name").toString()).getData();
            if (userItemName != null){
                return Result.fail(BizCode.NAME_ALREADY_EXIST);
            }
            MessageServiceImpl messageService = new MessageServiceImpl();
            String type = "加入团队";
            UserItem userItem = new UserItem();
            userItem.setName(dateMap.get("name").toString());
            if (dateMap.get("addType") != null && (!dateMap.get("addType").toString().equals("") || dateMap.get("addType").toString().equals("1"))){
                userItem.setUserId(Integer.parseInt(dateMap.get("userId").toString()));
                userItem.setUserIdOne(Integer.parseInt(dateMap.get("userIdOne").toString()));
                userItem.setUserIdTwo(Integer.parseInt(dateMap.get("userIdTwo").toString()));
                userItem.setUserIdThree(Integer.parseInt(dateMap.get("userIdThree").toString()));
            } else {
                userItem.setUserId(getUserId(dateMap.get("userName").toString()));
                if(!dateMap.get("itemName").toString().equals("")) {
                    userItem.setItemId(itemService.getItemByName(dateMap.get("itemName").toString()).getData().getId());
                }
            }
            userItem.setCreatedAt(new Date());
            userItem.setUpdatedAt(new Date());
            userItem.setIsDel(0);
            int i = this.userItemMapper.insert(userItem);
            if (i > 0){
                UserItem data = getUserItemByName(dateMap.get("name").toString()).getData();
                if (data.getUserIdOne() == null) {
                    messageService.sendMessage(type,getUserId(dateMap.get("userNameOne").toString()),data.getId());
                }
                if (data.getUserIdTwo() == null){
                    messageService.sendMessage(type,getUserId(dateMap.get("userNameTwo").toString()),data.getId());
                }
                if (data.getUserIdThree() == null){
                    messageService.sendMessage(type,getUserId(dateMap.get("userNameThree").toString()),data.getId());
                }
            }
            return Result.success(BizCode.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            log.error("添加团队信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result updateItem(Map dateMap) {
        try {
            UserItem userItem = new UserItem();
            userItem.setId(Integer.parseInt(dateMap.get("id").toString()));
            userItem.setName(dateMap.get("name").toString());
            userItem.setUserId(getUserId(dateMap.get("userName").toString()));
            userItem.setUserIdOne(getUserId(dateMap.get("userNameOne").toString()));
            userItem.setUserIdTwo(getUserId(dateMap.get("userNameTwo").toString()));
            userItem.setUserIdThree(getUserId(dateMap.get("userNameThree").toString()));
            userItem.setItemId(itemService.getItemByName(dateMap.get("itemName").toString()).getData().getId());
            userItem.setUpdatedAt(new Date());
            userItemMapper.updateById(userItem);
            return Result.success(BizCode.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            log.error("修改团队信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result deleteItem(Integer id) {
        try {
            String string = itemService.getAllItems(null, null, id, null, null, null, null).getData().getData().get(0).get("id").toString();
            int i = userItemMapper.deleteById(id);
            if (i > 0){
                itemMapper.deleteById(Integer.parseInt(string));
            }
            return Result.success(BizCode.SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            log.error("删除团队信息失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }
}
